import dayjs from 'dayjs';
import { formatOptions, xLabelStyle, yLabelStyle } from './formatter';
import type { Options, XType, YType, BaseNameDataObject } from './type';
import { formatDecimal } from './util';

interface YData extends BaseNameDataObject {
  tooltipData?: number[];
  total: number;
}

interface StackedAreaChartProps {
  selected: any;
  options: Options;
  xType: XType;
  yType: YType;
  tooltipType: YType;
  xData: number[] | string[];
  yData: YData[];
}

export const createStackedAreaOption = ({
  selected,
  options,
  xType,
  yType,
  tooltipType,
  xData,
  yData
}: StackedAreaChartProps) => {
  // 格式化options
  options = formatOptions(options);

  // 设定距离
  // const { maxValue, minValue } = getMaxAndMin(yData);
  // options.distance = getDistance(maxValue, minValue);

  return {
    // 暂时封存
    // grid: {
    //   left: 10 - options.distance, // 组件离容器左侧的距离
    //   right: 20, // 组件离容器右侧的距离
    //   top: 10, // 组件离容器上侧的距离
    //   bottom: 0, // 组件离容器下侧的距离
    //   containLabel: true, // grid区域是否包含坐标轴的刻度标签
    // },
    grid: {
      left: 40, // 组件离容器左侧的距离
      right: 20, // 组件离容器右侧的距离
      top: 10, // 组件离容器上侧的距离
      bottom: 25, // 组件离容器下侧的距离
      containLabel: false // grid区域是否包含坐标轴的刻度标签
    },
    legend: {
      show: false,
      selected
    },
    tooltip: {
      trigger: 'axis', // 坐标轴触发，折线图等会使用类目轴的图表中使用
      showDelay: 0, // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
      backgroundColor: 'rgba(0, 0, 0, 0.6)', // 背景颜色
      padding: 8,
      borderRadius: 6, // 边框圆角
      borderWidth: 0, // 边框宽度
      formatter: (params: any) => {
        // 副标题
        let subTitle = params[0].axisValue;
        if (xType === 'date') {
          subTitle = dayjs.unix(params[0].axisValue).format('MM/DD');
        } else if (xType === 'time') {
          subTitle = dayjs.unix(params[0].axisValue).format('MM/DD HH:mm');
        }
        const subTitleStr = `<div class="subtitle">${subTitle}</div>`;

        // 图例数据
        let itemStr = '';
        params
          ?.slice()
          .reverse()
          .forEach((item: any) => {
            let number = item.value;
            let unit = '';
            if (yType === 'percent') {
              // number = (number * 100).toFixed(2);
              number = formatDecimal(number, 2);
              unit = '%';
            } else if (yType === 'number') {
              // if (number > 10000) {
              //   number = parseFloat((number / 10000).toFixed(1));
              //   unit = "万";
              // }
            }

            if (tooltipType !== yType) {
              const series = yData[item.seriesIndex];
              const tooltipData = series.tooltipData;
              if (tooltipData?.length) {
                number = tooltipData[item.dataIndex];
                unit = '';
                if (tooltipType === 'percent') {
                  // number = (number * 100).toFixed(2);
                  number = formatDecimal(number, 2);
                  unit = '%';
                } else if (tooltipType === 'number') {
                  // if (number > 10000) {
                  //   number = parseFloat((number / 10000).toFixed(1));
                  //   unit = "万";
                  // }
                }
              }
            }

            itemStr += `<div class="row">
            <div class="sample" style="background: ${item.color}"></div>
            <div class="name">${item.seriesName}：</div>
            <div class="value">
              <div class="value-inner">
                <span class="unit">${unit}</span>
                <span class="number">${number.toLocaleString()}</span>
              </div>
            </div>
          </div>`;
          });

        const str = `<div class="chart-tooltip stacked-area">
          ${subTitleStr}
          ${itemStr}
        </div>`;

        return str;
      },
      axisPointer: {
        z: 0,
        lineStyle: {
          type: 'dashed',
          width: 2,
          color: '#C9CDD4'
        }
      } // 坐标轴指示器配置项，默认不显示，tooltip.trigger 设置为 'axis' 时会显示
    },
    color: yData.map((item) => item.color),
    xAxis: {
      type: 'category',
      triggerEvent: false, // 是否触发事件
      boundaryGap: true, // x坐标轴两边是否留白，不留白时，第一个和最后一个数据点会被遮挡
      axisLine: {
        show: true,
        lineStyle: {
          color: '#E5E6EC',
          type: 'solid'
        }
      }, // 坐标轴线
      axisTick: {
        show: false
      }, // 坐标轴刻度
      axisLabel: xLabelStyle(xType, options), // 坐标轴标签
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: yLabelStyle(yType, options), // 坐标轴标签
      splitLine: {
        show: true,
        lineStyle: {
          color: '#E5E6EC',
          type: 'dashed'
        }
      } // 分割线
    },
    series: yData.map((item) => {
      return {
        type: 'line',
        data: item.data,
        name: item.name,
        yAxisIndex: 0,
        lineStyle: {
          color: item.color
        },
        emphasis: {
          focus: 'none'
        },
        stack: 'Total',
        areaStyle: {},
        showSymbol: false,
        symbolSize: 10
      };
    })
  };
};
